package cn.edu.nju.ws.sview.views.listener;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Calendar;
import java.util.Date;
import java.util.TimerTask;

import cn.edu.nju.ws.sview.database.DBConnectionFactory;
import cn.edu.nju.ws.sview.views.data.EntityManagement;

/**
 * 每天晚上10点定时清空明天对应的上周那天已有的实体访问信息
 * 涉及表clear_info
 * @author ssgong
 *
 */
public class EntityDayVisitClearTask extends TimerTask{
	 public void run() {
		  Calendar d=Calendar.getInstance();
		  int day_of_week = d.get(Calendar.DAY_OF_WEEK)-1;
		  int clear_day = day_of_week+1;
		  if(clear_day>6){
			  clear_day = 0;
		  }
		  int h = d.get(Calendar.HOUR_OF_DAY) ;
		  if(h>=22){
			 try {
				 Connection con = DBConnectionFactory.getConnection();
				PreparedStatement stmt = con.prepareStatement("select null from clear_info where name=? and time=?") ;
				stmt.setString(1, EntityManagement.CLEAR_ENTITY_POPULARITY) ;
				java.sql.Date date = new java.sql.Date(new Date().getTime());
				stmt.setDate(2, date) ;
				ResultSet rs = stmt.executeQuery();
				boolean flag = false;
				if(rs.next())
					flag = true;
				if(!flag){
					Statement delstmt = con.createStatement();
					delstmt.executeUpdate("delete from user_day_visit where date="+clear_day);
					delstmt.close();
					PreparedStatement insertStmt = con.prepareStatement("insert into clear_info values(?,?) on duplicate key update time=values(time)") ;
					insertStmt.setString(1, EntityManagement.CLEAR_ENTITY_POPULARITY);
					insertStmt.setDate(2, new java.sql.Date(new Date().getTime())) ;
					insertStmt.executeUpdate();
					insertStmt.close();
				}
				rs.close();
				stmt.close();
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		  }
	  }
}
